import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_study_2025/aes/aes_utils.dart';
import 'package:http/http.dart' as http;
import 'login_api.dart';

class LoginTestPage extends StatefulWidget {
  const LoginTestPage({super.key});

  @override
  State<LoginTestPage> createState() => _LoginTestPageState();
}

class _LoginTestPageState extends State<LoginTestPage> {
  final _formKey = GlobalKey<FormState>();
  final _accountController = TextEditingController();
  final _passwordController = TextEditingController();
  final _loginTypeController = TextEditingController();
  final _platformIdController = TextEditingController();

  bool _isLoading = false;
  String _responseText = '';
  bool _isPasswordVisible = false;

  @override
  void initState() {
    super.initState();
    // 设置默认值
    _accountController.text = '123919143@qq.com';
    _passwordController.text = 'testpass';
    _loginTypeController.text = 'string';
    _platformIdController.text = '0';
  }

  @override
  void dispose() {
    _accountController.dispose();
    _passwordController.dispose();
    _loginTypeController.dispose();
    _platformIdController.dispose();
    super.dispose();
  }

  Future<void> _testLogin() async {
    var headers = {'Content-Type': 'application/json-patch+json'};
    var request = http.Request(
      'POST',
      Uri.parse('https://api.misstory789.online/api/asf/ComicMember/Login'),
    );
    var body = json.encode({
      "accountName": "123919143@qq.com",
      "passWord": "qwer1234",
      "loginType": "0",
      "platformId": 1,
    });
    // body转String
    // final String value = AESUtil.encryptECB(body.toString());
    request.body = body;
    request.headers.addAll(headers);

    final response = await request.send();

    if (response.statusCode == 200) {
      print(await response.stream.bytesToString());
    } else {
      print(response.reasonPhrase);
    }

    // if (!_formKey.currentState!.validate()) {
    //   return;
    // }

    // setState(() {
    //   _isLoading = true;
    //   _responseText = '正在发送请求...';
    // });

    // try {
    //   final result = await LoginAPI.login(
    //     accountName: "123919143@qq.com",
    //     password: _passwordController.text.trim(),
    //     loginType: _loginTypeController.text.trim().isEmpty
    //         ? null
    //         : _loginTypeController.text.trim(),
    //     platformId: _platformIdController.text.trim().isEmpty
    //         ? null
    //         : int.tryParse(_platformIdController.text.trim()),
    //   );

    //   setState(() {
    //     _responseText = _formatResponse(result);
    //   });
    // } catch (e) {
    //   setState(() {
    //     _responseText = '请求异常: $e';
    //   });
    // } finally {
    //   setState(() {
    //     _isLoading = false;
    //   });
    // }
  }

  String _formatResponse(Map<String, dynamic> response) {
    final buffer = StringBuffer();
    buffer.writeln('=== 登录测试结果 ===');
    buffer.writeln('请求状态: ${response['success'] ? '成功' : '失败'}');
    buffer.writeln('状态码: ${response['statusCode']}');
    buffer.writeln('消息: ${response['message']}');
    buffer.writeln();

    if (response['data'] != null) {
      buffer.writeln('响应数据:');
      try {
        final prettyJson = const JsonEncoder.withIndent(
          '  ',
        ).convert(response['data']);
        buffer.writeln(prettyJson);
      } catch (e) {
        buffer.writeln(response['data'].toString());
      }
    }

    if (response['error'] != null) {
      buffer.writeln();
      buffer.writeln('错误详情:');
      buffer.writeln(response['error']);
    }

    return buffer.toString();
  }

  void _copyResponse() {
    if (_responseText.isNotEmpty) {
      Clipboard.setData(ClipboardData(text: _responseText));
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('响应内容已复制到剪贴板')));
    }
  }

  void _clearResponse() {
    setState(() {
      _responseText = '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录接口测试'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () {
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('接口信息'),
                  content: const Text(
                    'API地址:\nhttp://dev-cn.your-api-server.com/ComicMember/Login\n\n'
                    '请求方式: POST\n'
                    'Content-Type: application/json-patch+json',
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: const Text('确定'),
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '登录参数',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 16),
                      TextFormField(
                        controller: _accountController,
                        decoration: const InputDecoration(
                          labelText: '账户名 *',
                          hintText: '请输入账户名',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.person),
                        ),
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return '请输入账户名';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 12),
                      TextFormField(
                        controller: _passwordController,
                        obscureText: !_isPasswordVisible,
                        decoration: InputDecoration(
                          labelText: '密码 *',
                          hintText: '请输入密码',
                          border: const OutlineInputBorder(),
                          prefixIcon: const Icon(Icons.lock),
                          suffixIcon: IconButton(
                            icon: Icon(
                              _isPasswordVisible
                                  ? Icons.visibility
                                  : Icons.visibility_off,
                            ),
                            onPressed: () {
                              setState(() {
                                _isPasswordVisible = !_isPasswordVisible;
                              });
                            },
                          ),
                        ),
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return '请输入密码';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 12),
                      TextFormField(
                        controller: _loginTypeController,
                        decoration: const InputDecoration(
                          labelText: '登录类型 (可选)',
                          hintText: '如: string',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.category),
                        ),
                      ),
                      const SizedBox(height: 12),
                      TextFormField(
                        controller: _platformIdController,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: '平台ID (可选)',
                          hintText: '如: 0',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.devices),
                        ),
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                      ),
                      const SizedBox(height: 20),
                      SizedBox(
                        width: double.infinity,
                        height: 48,
                        child: ElevatedButton(
                          onPressed: _isLoading ? null : _testLogin,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                            foregroundColor: Colors.white,
                          ),
                          child: _isLoading
                              ? const Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    SizedBox(
                                      width: 20,
                                      height: 20,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        valueColor:
                                            AlwaysStoppedAnimation<Color>(
                                              Colors.white,
                                            ),
                                      ),
                                    ),
                                    SizedBox(width: 8),
                                    Text('测试中...'),
                                  ],
                                )
                              : const Text(
                                  '测试登录接口',
                                  style: TextStyle(fontSize: 16),
                                ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            const SizedBox(height: 16),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        const Text(
                          '响应结果',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const Spacer(),
                        if (_responseText.isNotEmpty) ...[
                          IconButton(
                            icon: const Icon(Icons.copy),
                            onPressed: _copyResponse,
                            tooltip: '复制响应',
                          ),
                          IconButton(
                            icon: const Icon(Icons.clear),
                            onPressed: _clearResponse,
                            tooltip: '清空响应',
                          ),
                        ],
                      ],
                    ),
                    const SizedBox(height: 12),
                    Container(
                      width: double.infinity,
                      height: 300,
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        border: Border.all(color: Colors.grey[300]!),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: _responseText.isEmpty
                          ? const Center(
                              child: Text(
                                '点击"测试登录接口"按钮查看响应结果',
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontStyle: FontStyle.italic,
                                ),
                              ),
                            )
                          : SingleChildScrollView(
                              child: SelectableText(
                                _responseText,
                                style: const TextStyle(
                                  fontFamily: 'monospace',
                                  fontSize: 12,
                                ),
                              ),
                            ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }
}
